package com.bds.btcdc.web.service;

import com.bds.btcdc.web.model.*;
import com.bds.btcdc.web.utils.Const;
import org.apache.log4j.Logger;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by DongChenchen on 2018/4/25 0025
 */
@Service
public class ExchangeService {
    private Logger LOGGER = org.apache.log4j.Logger.getLogger(getClass());
    @Resource
    private NutDao dao;

    public List<TExchange> getAll(){
        return dao.query(TExchange.class, Cnd.where("state", "=", 1));
    }

    /**
     *获取的exchange,其中费率，按照t_user_rate表中的值（存在的情况下）
     * @return
     */
    public List<TExchange> getExchangeNoInUserRate(Long userId){
        List<TExchange> exchanges = dao.query(TExchange.class, Cnd.where("state", "=", 1));
        List<TUserRate> userRates = dao.query(TUserRate.class, Cnd.where("user_id", "=", userId));
        if(!CollectionUtils.isEmpty(userRates)) {
            Map<String, TUserRate> codes = new HashMap<>();
            for (TUserRate rate : userRates) {
                codes.put(rate.getCode(), rate);
            }
            for (TExchange ex : exchanges) {
                if (codes.keySet().contains(ex.getCode())) {
                    TUserRate tUserRate = codes.get(ex.getCode());
                    ex.setRate(tUserRate.getRate());
                }
            }
        }
        return exchanges;
    }

    public TExchange getExchangeByCode(String code){
        return dao.fetch(TExchange.class, Cnd.where("code", "=", code));
    }

    public void test(){
        dao.create(TExchange.class,false);
    }

    public List<MarketData> initExchange(){
        List<CoinPairExchanges> bit_pairs= getPairs("bitstamp");
        List<CoinPairExchanges> zb_pairs= getPairs("zb");
        List<CoinPairExchanges> huoBi_pairs=getPairs("HuoBi");
        List<CoinPairExchanges> okex_pairs= getPairs("OKEX");
        List<CoinPairExchanges> okcoin_pairs= getPairs("okcoin");
        List<CoinPairExchanges> giteio_pairs= getPairs("gateio");
        List<CoinPairExchanges> init_list = new ArrayList<>();
        init_list.addAll(bit_pairs);
        init_list.addAll(zb_pairs);
        init_list.addAll(huoBi_pairs);
        init_list.addAll(okex_pairs);
        init_list.addAll(okcoin_pairs);
        init_list.addAll(giteio_pairs);
        List<MarketData> data_list = new ArrayList<MarketData>();
        for (int i = 0; i < init_list.size(); i++) {
            CoinPairExchanges pair=init_list.get(i);
            MarketData data=new MarketData();
            data.setExchange(pair.getExchange().toLowerCase());
            data.setPair(pair.getEn_pair_code());
            data.setLast("");
            data.setHigh("");
            data.setLow("");
            data.setBuy("");
            data.setSell("");
            data.setVol("");
            data_list.add(data);
        }
        return data_list;
    }

    /**
     * 返回系统支持的交易所名称列表
     */
    public List<String> listExchange(){
        Sql sql = Sqls.create("SELECT DISTINCT exchange FROM t_coin_pair_exchanges");
        sql.setCallback(new SqlCallback() {
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                List<String> list = new LinkedList<String>();
                while (rs.next())
                    list.add(rs.getString("exchange"));
                return list;
            }
        });
        dao.execute(sql);
        List<String> list = sql.getList(String.class);
        return list;
    }

    /**
     * 返回交易所下支持的所有币对，只取币对名称
     * @param exchange
     * @return
     */
    public List<String> exchangePairs(String exchange) {
        Sql sql = Sqls.create("Select b.en_pair_code " +
                "from t_coin_pair a,t_coin_pair_exchanges b " +
                "where a.STATUS=1 " +
                "and a.en_pair_code=b.en_pair_code " +
                "and b.exchange=@exchange");
        sql.params().set("exchange", exchange);
        sql.setCallback(new SqlCallback() {
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                List<String> list = new LinkedList<String>();
                while (rs.next())
                    list.add(rs.getString(1));
                return list;
            }
        });
        dao.execute(sql);
        List<String> list = sql.getList(String.class);
        return list;
    }

    /**
     * 查询channel交易所
     * 支持对冲平台的币对
     * @return
     */
    public List<CoinPairExchanges> getPairs(String exchange) {

        Sql sql = Sqls.create("Select b.* " +
                "from t_coin_pair a,t_coin_pair_exchanges b " +
                "where a.STATUS=1 " +
                "and a.en_pair_code=b.en_pair_code " +
                "and b.exchange=@exchange");
        sql.params().set("exchange", exchange);
        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(CoinPairExchanges.class));
        dao.execute(sql);
        return sql.getList(CoinPairExchanges.class);
    }

}
